#pragma once

#include "Socket.hpp"
#include <iostream>
#include <memory>
#include <sys/wait.h>
#include <functional>

typedef std::function<void(std::shared_ptr<Socket>&, InetAddr&)> ioservice_t; 

class TcpServer
{
public:
    TcpServer(uint16_t port, ioservice_t service)
        :_port(port)
        , _service(service)
    {
        _listensockptr->BuildTcpListenSocket(_port);
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            auto sock = _listensockptr->Accept(&client);
            if(sock == nullptr)
            {
                continue;
            }
            LOG(LogLevel::INFO) << "accept success";
            
            pid_t id = fork();
            if(id < 0)
            {
                LOG(LogLevel::FATAL) << "fork error";
                exit((int)exit_code::FORK_ERR);
            }
            else if(id == 0)
            {
                _listensockptr->Close();
                if(fork() > 0) exit(0);

                _service(sock, client);
                sock->Close();
                exit(0);
            }
            else
            {
                sock->Close();
                waitpid(id, nullptr, 0);
            }
        }
        _isrunning = false;
    }
private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr = std::make_unique<TcpSocket>();
    bool _isrunning = false;
    ioservice_t _service;
};